import { createSlice,createAsyncThunk } from '@reduxjs/toolkit'
import { request,login } from '../../utils/request'
const userStore = createSlice({
  name: 'user',
  initialState: {
    userInfo: {},
    allUserInfo: [],
    token:'',
  },
  reducers: {
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },
    setToken(state, action) {
      state.token = action.payload
    },
    setAllUserInfo(state, action) {
      state.allUserInfo = action.payload
    },
  },
})

// 异步获取
const fetchLogin = createAsyncThunk(
  'user/fetchLogin',
  async (loginInfo, { rejectWithValue }) => {
    try {
      // 向后端服务器发送请求
      // console.log(loginInfo);
      const response = await login(loginInfo.username, loginInfo.password, loginInfo.role);
      console.log('准备跳转');
      // if (!response.data?.redirectUrl) {
      //   throw new Error('服务器未返回重定向URL');
      // }
      // window.location.href = response.data.redirectUrl;
      
      return response;
      
    } catch (error) {
      return rejectWithValue(error.response?.data || error.message);
    }
  }
);
const fetchUserInfo = (loginInfo) => {
  return async (dispatch) => {
    console.log(loginInfo);
    // 2.运用action进行同步操作
    dispatch(setUserInfo(loginInfo))
  }
}
const fetchAllUserInfo = () => {
  return async (dispatch) => {
    const res = await request.get('/user')
    console.log(res);
    
    // 2.运用action进行同步操作
    dispatch(setAllUserInfo(res))
  }
  
}


// 解构出来的方法
const { setUserInfo,setToken,setAllUserInfo } = userStore.actions
const reducer = userStore.reducer



export { setUserInfo,setToken,setAllUserInfo,fetchLogin,fetchUserInfo,fetchAllUserInfo }
export default reducer